package controllers

import (
	"bsm/logger"
	"bsm/middleware"
	"bsm/models"
	"bsm/services"
	"net/http"

	"github.com/gin-gonic/gin"
)

type UserController interface {
	GetProfile(c *gin.Context)
	ChangePassword(c *gin.Context)
	CheckUserRole(c *gin.Context)
}

type userControllerImpl struct {
	userService services.UserService
}

func NewUserController(userService services.UserService) UserController {
	return &userControllerImpl{
		userService: userService,
	}
}

// GetProfile 获取用户个人信息
func (uc *userControllerImpl) GetProfile(c *gin.Context) {
	// 从中间件获取当前用户ID
	userID := middleware.GetCurrentUserID(c)
	if userID == "" {
		logger.WithFields(map[string]interface{}{
			"layer":     "controller",
			"operation": "UserController-GetProfile",
			"userID":    userID,
		}).Error("未授权访问")
		c.JSON(http.StatusUnauthorized, gin.H{"信息": "未授权访问"})
		return
	}

	// 调用服务层获取用户信息
	user, err := uc.userService.GetUserProfile(userID)
	if err != nil {
		logger.WithFields(map[string]interface{}{
			"layer":     "controller",
			"operation": "UserController-GetProfile",
			"userID":    userID,
		}).Error("获取用户信息失败: " + err.Error())
		c.JSON(http.StatusInternalServerError, gin.H{"信息": "获取用户信息失败"})
		return
	}

	if user == nil {
		c.JSON(http.StatusNotFound, gin.H{
			"code": 404,
			"msg":  "用户不存在",
		})
		return
	}

	// 返回用户信息（可以过滤敏感信息）
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "success",
		"data": gin.H{
			"id":       user.ID,
			"name":     user.UserID,
			"org_code": user.OrgCode,
			// 可以根据需要添加更多字段
		},
	})
}

// UpdateProfile 更新用户信息
// func (uc *UserController) UpdateProfile(c *gin.Context) {
// 	userID := middleware.GetCurrentUserID(c)
// 	if userID == 0 {
// 		c.JSON(http.StatusUnauthorized, gin.H{
// 			"code": 401,
// 			"msg":  "未授权访问",
// 		})
// 		return
// 	}

// 	var updateData struct {
// 		Name  string `json:"name" binding:"required"`
// 		Email string `json:"email" binding:"required,email"`
// 	}

// 	if err := c.ShouldBindJSON(&updateData); err != nil {
// 		c.JSON(http.StatusBadRequest, gin.H{
// 			"code": 400,
// 			"msg":  "参数错误: " + err.Error(),
// 		})
// 		return
// 	}

// 	// 调用服务层更新用户信息
// 	err := uc.userService.UpdateUserProfile(userID, map[string]interface{}{
// 		"name":  updateData.Name,
// 		"email": updateData.Email,
// 	})
// 	if err != nil {
// 		c.JSON(http.StatusInternalServerError, gin.H{
// 			"code": 500,
// 			"msg":  "更新用户信息失败: " + err.Error(),
// 		})
// 		return
// 	}

// 	c.JSON(http.StatusOK, gin.H{
// 		"code": 0,
// 		"msg":  "用户信息更新成功",
// 	})
// }

// ChangePassword 修改密码
func (uc *userControllerImpl) ChangePassword(c *gin.Context) {
	userID := middleware.GetCurrentUserID(c)
	if userID == "" {
		c.JSON(http.StatusUnauthorized, gin.H{
			"code": 401,
			"msg":  "未授权访问",
		})
		return
	}

	var passwordData struct {
		OldPassword string `json:"old_password" binding:"required"`
		NewPassword string `json:"new_password" binding:"required,min=6"`
	}

	if err := c.ShouldBindJSON(&passwordData); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "参数错误: " + err.Error(),
		})
		return
	}

	// 调用服务层修改密码
	err := uc.userService.ChangePassword(userID, passwordData.OldPassword, passwordData.NewPassword)
	if err != nil {
		logger.WithFields(map[string]interface{}{
			"layer":     "controller",
			"operation": "UserController-ChangePassword",
			"userID":    userID,
		}).Error("修改密码失败: " + err.Error())
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "修改密码失败: " + err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "密码修改成功",
	})
}

func (uc *userControllerImpl) CheckUserRole(c *gin.Context) {
	userID := middleware.GetCurrentUserID(c)
	if userID == "" {
		logger.WithFields(map[string]interface{}{
			"layer":     "controller",
			"operation": "RoleController-CheckUserRole",
			"userID":    userID,
		}).Error("未授权访问")
		c.JSON(http.StatusUnauthorized, models.Response{
			Code:    401,
			Message: "未授权访问",
		})
		return
	}

	type reqStruct struct {
		UserID string `json:"user_id"`
		RoleID string `json:"role_id"`
	}
	var req reqStruct
	if err := c.ShouldBindJSON(&req); err != nil {
		logger.WithFields(map[string]interface{}{
			"layer":     "controller",
			"operation": "RoleController-CheckUserRole",
			"userID":    userID,
		}).Error("参数绑定失败")
		c.JSON(http.StatusBadRequest, models.Response{
			Code:    400,
			Message: "参数绑定失败",
		})
		return
	}
	// 调用服务层检查用户角色
	hasRole, err := uc.userService.CheckUserRole(req.UserID, req.RoleID)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "检查用户角色失败: " + err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, models.Response{
		Code:    0,
		Message: "success",
		Data:    hasRole,
	})
}
